package com.xingdata.jjxc.map.navi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.autonavi.tbt.NaviStaticInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.base.ComBaseActivity;
import com.xingdata.jjxc.enty.ComAddressEntity;
import com.xingdata.jjxc.enty.HUDParameterEntity;
import com.xingdata.jjxc.m.avt.ComAddressSetavt;
import com.xingdata.jjxc.map.navi.IATController;
import com.xingdata.jjxc.map.navi.TTSController;
import com.xingdata.jjxc.map.navi.activity.util.Utils;
import com.xingdata.jjxc.speech.IatActivity;
import com.xingdata.jjxc.utils.Constants;
import com.xingdata.jjxc.utils.JsonParser;
import com.xingdata.jjxc.utils.Log;
import com.xingdata.jjxc.utils.LongitudeAndLatitudeTools;
import com.xingdata.jjxc.utils.SDCardTools;
import com.xingdata.jjxc.utils.StringUtil;
import com.xingdata.jjxc.utils.SystemInfo;

/**
 * 
 * 项目名称：JJXC_VPN 类名称：NaviLocationActivity 类描述： 导航定位页面 创建人：JiangMin 创建时间：2015-5-6
 * 下午12:09:32 修改备注：
 * 
 * @version
 * 
 */
public class NaviLocationActivity extends ComBaseActivity implements LocationSource, AMapLocationListener, OnMapClickListener, OnGeocodeSearchListener, TextWatcher, OnItemClickListener, OnMarkerClickListener, OnClickListener, OnInfoWindowClickListener, InfoWindowAdapter, AMapNaviListener, OnPoiSearchListener {
	private String TAG = "NaviLocationActivity";
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	// private LocationManagerProxy mAMapLocationManager;
	// 搜索框
	private EditText serchEditText;
	// 搜索适配器
	private ArrayAdapter<String> serchAdapter;
	// 搜索重新封装的数据
	private List<Tip> tips = new ArrayList<Tip>();
	private Bundle mBundle;
	// 适配器中的数据
	private List<String> adaList = null;
	private View pop_view;
	// 驾车路径规划起点，途经点，终点的list
	private List<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
	// 记录起点、终点、途经点位置
	private NaviLatLng mStartPoint = new NaviLatLng();
	private NaviLatLng mEndPoint = new NaviLatLng();

	// 记录起点、终点、途经点在地图上添加的Marker
	private Marker mStartMarker;
	// private Marker mWayMarker;
	private Marker mEndMarker;
	// private Marker mGPSMarker;
	private PopupWindow navigationPopupWindow = null;
	// 坐标/地名转换
	private GeocodeSearch geocoderSearch;
	// 记录地图点击事件相应情况，根据选择不同，地图响应不同
	private int mMapClickMode = MAP_CLICK_NO;
	private static final int MAP_CLICK_NO = 0;// 地图不接受点击事件
	private static final int MAP_CLICK_END = 3;// 地图点击设置终点
	// 规划线路
	private RouteOverLay mRouteOverLay;
	// 是否驾车和是否计算成功的标志
	private boolean mIsDriveMode = true;
	private boolean mIsCalculateRouteSuccess = false;
	private AMapNavi mAMapNavi;
	private List<String> aMapNaviGuides = null;
	// 是否真实导航 true模拟导航
	private Boolean isNaviRote = true;
	private String strAddress = "";
	private boolean isGetInfoWindow = false;
	// 判断是从哪里进来的 0 导航收藏添加 1 常用地址导航 2导航
	private int inNaviLocionType = 0;
	private ComAddressEntity mAddressEntity = null;
	// 总路长
	private String strAllLength;
	private Boolean isCalculateSuccess = false;
	// private UartService service;
	private int IatrequestCode = 2;
	private IATController iatController;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	private Boolean isBack = true;
	private boolean isSerch = true;
	private String[] redundantCharacter = { "到", "往", "去" };
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	private PoiResult poiResult; // poi返回的结果
	private int currentPage = 0;// 当前页面，从0开始计数
	private ImageView seachButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
		 * 设置离线地图存储目录，在下载离线地图或初始化地图设置; 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
		 * 则需要在离线地图下载和使用地图页面都进行路径设置
		 */
		// Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
		MapsInitializer.sdcardDir = SDCardTools.getFilePath(SDCardTools.OFFLINE_MAP);
		setContentView(R.layout.activity_locationsource);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);
		initViews();
		initMapAndNavi();
		initIATController();
	}

	private void initIATController() {
		iatController = IATController.getInstance(this, recognizerDialogListener);

	}

	@Override
	protected void initViews() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			inNaviLocionType = bundle.getInt("inNaviLocionType");
		}
		mMapClickMode = MAP_CLICK_END;
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
		mAMapNavi = AMapNavi.getInstance(this);
		mAMapNavi.setAMapNaviListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
		serchEditText = (EditText) findViewById(R.id.com_search_map_et);
		geocoderSearch = new GeocodeSearch(this);
		// ImageView Speech_Navi = ((ImageView) findViewById(R.id.Speech_Navi));
		((Button) findViewById(R.id.goBack)).setOnClickListener(this);
		// Speech_Navi.setOnClickListener(this);
		// 输入提示的监听接口
		// serchEditText.addTextChangedListener(this);
		// serchEditText.setOnItemClickListener(this);
		// 地名搜索监听接口
		geocoderSearch.setOnGeocodeSearchListener(this);

		// seachButton = (ImageView) findViewById(R.id.seachButton);
		// seachButton.setOnClickListener(this);
		// TTSController ttsManager = TTSController.getInstance(this);// 初始化语音模块
		// ttsManager.init();
		AMapNavi.getInstance(this).setAMapNaviListener(TTSController.getInstance(this));//

	}

	/**
	 * 初始化地图和导航相关内容
	 */
	private void initMapAndNavi() {
		// 初始化Marker添加到地图
		mStartMarker = aMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.start))));
		MarkerOptions endMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.end))).title("");
		endMarkerOptions.draggable(true);
		mEndMarker = aMap.addMarker(endMarkerOptions);
		mRouteOverLay = new RouteOverLay(aMap, null, this);
		if (inNaviLocionType == Constants.inNaviLocionType_COMMON) {
			mAddressEntity = (ComAddressEntity) getIntent().getExtras().getSerializable("ComAddressEntity");
			mEndPoint.setLatitude(Double.parseDouble(mAddressEntity.getLatitude()));
			mEndPoint.setLongitude(Double.parseDouble(mAddressEntity.getLongitude()));
			// 其他情况根据起点、途经点、终点不同逻辑处理不同
			addPointToMap(new LatLng(mEndPoint.getLatitude(), mEndPoint.getLongitude()));
			isGetInfoWindow = true;
			mEndMarker.showInfoWindow();
		}
	}

	/**
	 * 根据地名艘搜索坐标 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
	 */
	private void geocodeQuery(String address, String cityCode) {
		GeocodeQuery query = new GeocodeQuery(address, cityCode);
		geocoderSearch.getFromLocationNameAsyn(query);
	}

	/**
	 * 根据坐标点搜索地名 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
	 */
	private void regeocodeQuery(LatLonPoint latLonPoint) {
		// 清空输入框的内容
		serchEditText.setText("");
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
		// 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
		// type - 定位的类型。提供3种类型，分别为：LOCATION_TYPE_LOCATE
		// 表示只在第一次定位移动到地图中心点，值为1；LOCATION_TYPE_MAP_FOLLOW 表示定位、移动到地图中心点并跟随，值为2和
		// LOCATION_TYPE_MAP_ROTATE 表示定位、移动到地图中心点，跟踪并根据方向旋转地图，值为3。
		if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
		}
		aMap.setOnMapClickListener(this);
		aMap.setMapType(SystemTools.isNight() ? AMap.MAP_TYPE_NIGHT : AMap.MAP_TYPE_NORMAL);
		aMap.setOnMarkerClickListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
	}

	// @Override
	// public void onLocationChanged(Location arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderDisabled(String arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderEnabled(String arg0) {
	// // TODO Auto-generated method stub
	//
	// }

	// @Override
	// public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
	// // TODO Auto-generated method stub
	//
	// }

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {

		if (mListener != null && amapLocation != null) {
			if (amapLocation.getErrorCode() == 0) {
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				mStartPoint.setLatitude(amapLocation.getLatitude());
				mStartPoint.setLongitude(amapLocation.getLongitude());
				mStartPoints.add(mStartPoint);
				SystemInfo.City = amapLocation.getCity();
			}

			initMapAndNavi();
			// 本地定位成功之后才开始计算路径
			// if (inNaviLocionType==Constants.inNaviLocionType_COMMON) {
			// calculateDriveRoute();
			// }
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		// mListener = listener;
		// if (mAMapLocationManager == null) {
		// mAMapLocationManager = LocationManagerProxy.getInstance(this);
		// // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// // 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// // 在定位结束后，在合适的生命周期调用destroy()方法
		// // 其中如果间隔时间为-1，则定位只定一次
		// mAMapLocationManager.requestLocationData(
		// LocationProviderProxy.AMapNetwork, -1, 10, this);
		// }
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		// mListener = null;
		// if (mAMapLocationManager != null) {
		// mAMapLocationManager.removeUpdates(this);
		// mAMapLocationManager.destroy();
		// }
		// mAMapLocationManager = null;
	}

	/**
	 * 此方法需存在
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		TTSController.getInstance(this).playText("退出导航");
		mapView.onDestroy();
		// 删除监听
		AMapNavi.getInstance(this).removeAMapNaviListener(this);
		// 这是最后退出页，所以销毁导航和播报资源
		AMapNavi.getInstance(this).destroy();// 销毁导航
		TTSController.getInstance(this).stopSpeaking();
		TTSController.getInstance(this).destroy();
		if (iatController != null) {
			iatController.onDestory();
		}

	}

	@Override
	public void onMapClick(LatLng latLng) {
		// 默认不接受任何操作
		if (mMapClickMode == MAP_CLICK_NO || Constants.inNaviLocionType_COMMON == inNaviLocionType) {
			return;
		}

		// 其他情况根据起点、途经点、终点不同逻辑处理不同
		addPointToMap(latLng);
		regeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude));
		Log.i(TAG, "latitude:" + latLng.latitude + " longitude:" + latLng.longitude);

	}

	/**
	 * 画出坐标点
	 * 
	 * @param latLng
	 */
	private void addPointToMap(LatLng latLng) {

		NaviLatLng naviLatLng = new NaviLatLng(latLng.latitude, latLng.longitude);
		switch (mMapClickMode) {
		// 终点
		case MAP_CLICK_END:
			animateCameraToCenter(latLng);
			mEndMarker.setPosition(latLng);
			mEndPoints.clear();
			mEndPoint = naviLatLng;
			mEndPoints.add(mEndPoint);
			break;
		}

	}

	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null && result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				strAddress = address.getFormatAddress();
				// 搜索完毕后根据坐标点画出
				addPointToMap(new LatLng(address.getLatLonPoint().getLatitude(), address.getLatLonPoint().getLongitude()));
				// showToast(strAddress);
				// View infoWindow = getLayoutInflater().inflate(
				// R.layout.pop_car_address_set, null);
				// ((TextView) infoWindow
				// .findViewById(R.id.pop_company_addressset_tv)).setText(strAddress);
				isGetInfoWindow = true;
				mEndMarker.showInfoWindow();
			} else {
				showToast("没有搜索到结果");
				strAddress = "";
			}

		} else {
			strAddress = "";
			showToast("网络异常");
		}
	}

	/**
	 * 将固定坐标点移动到中心位置
	 * 
	 * @param latLng
	 */
	private void animateCameraToCenter(LatLng latLng) {
		float f = 15;
		int w = StringUtil.getScreenWidthPixels(this);
		if (w == 1280) {
			f = 14;
		} else if (w < 1280) {
			f = 13;
		}
		aMap.animateCamera(new com.amap.api.maps.CameraUpdateFactory().newLatLngZoom(latLng, f));
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
				strAddress = result.getRegeocodeAddress().getFormatAddress();
				// showToast(strAddress);
				// 搜索成功后清空输入框
				serchEditText.setText("");
				isGetInfoWindow = true;
				mEndMarker.showInfoWindow();
			} else {
				strAddress = "";
				showToast("没有搜索到地址");
			}
		} else {
			strAddress = "";
			showToast("网络异常");
		}
	}

	// 输入信息改变之后
	@Override
	public void afterTextChanged(Editable s) {

	}

	// 输入信息改变之前
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	// 正在输入
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String newText = "";
		if (s != null) {
			newText = s.toString();
		}
		// 输入信息的回调方法
		Inputtips inputTips = new Inputtips(NaviLocationActivity.this, new InputtipsListener() {
			@Override
			public void onGetInputtips(List<Tip> tipList, int rCode) {

				if (rCode == 0) {// 正确返回
					if (adaList == null) {
						adaList = new ArrayList<String>();
					}
					adaList.clear();
					tips = tipList;
					for (int i = 0; i < tipList.size(); i++) {
						adaList.add(tipList.get(i).getName());
					}
					ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.route_inputs, adaList);
					// serchEditText.setAdapter(aAdapter);
					aAdapter.notifyDataSetChanged();
				}
				// if (rCode==0) {
				// if (adaList==null) {
				// adaList= new ArrayList<String>();
				// }
				// adaList.clear();
				// for (Tip tip : tipList) {
				// adaList.add(tip.getName());
				// Log.i(TAG, "name :" + tip.getName());
				// }
				// serchAdapter = new ArrayAdapter<String>(
				// NaviLocationActivity.this,
				// android.R.layout.simple_dropdown_item_1line,
				// R.layout.route_inputs, adaList);
				// serchEditText.setAdapter(serchAdapter);
				// serchAdapter.notifyDataSetChanged();
				// }

			}
		});

		// 发送输入提示请求
		// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号
		try {
			inputTips.requestInputtips(newText, SystemInfo.City);
		} catch (com.amap.api.services.core.AMapException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		geocodeQuery(tips.get(position).getName(), tips.get(position).getAdcode());
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		// return showPOP(marker);
		return false;
	}

	/**
	 * 现实POP
	 * 
	 * @param marker
	 * @return
	 */
	private boolean showPOP(Marker marker) {
		switch (mMapClickMode) {
		case MAP_CLICK_END:
			if (navigationPopupWindow == null) {
				navigationPopupWindow = new PopupWindow(this);
				pop_view = View.inflate(this, R.layout.popupwindow_navigation, null);
				navigationPopupWindow.setContentView(pop_view);
				navigationPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
				navigationPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
				navigationPopupWindow.setFocusable(true);
				navigationPopupWindow.setOutsideTouchable(false);
				navigationPopupWindow.setAnimationStyle(R.style.popup_fade_anim);
				// 20%黑
				ColorDrawable dw = new ColorDrawable(0x33000000);
				navigationPopupWindow.setBackgroundDrawable(dw);
				pop_view.setOnTouchListener(new OnTouchListener() {
					public boolean onTouch(View v, MotionEvent event) {
						int height = pop_view.findViewById(R.id.pop_layout).getTop();
						int y = (int) event.getY();
						if (event.getAction() == MotionEvent.ACTION_UP) {
							if (y < height) {
								navigationPopupWindow.dismiss();
							}
						}
						return true;
					}
				});
				pop_view.findViewById(R.id.pop_begin).setOnClickListener(this);
				pop_view.findViewById(R.id.pop_simulate).setOnClickListener(this);
			}
			navigationPopupWindow.showAtLocation(this.findViewById(R.id.com_search_map_et), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

			break;

		default:
			break;
		}

		return false;

	}

	@Override
	public void onClick(View v) {
		mIsCalculateRouteSuccess = false;
		isCalculateSuccess = false;
		mIsDriveMode = true;
		switch (v.getId()) {
		// 导航
		case R.id.pop_begin:
			isNaviRote = false;
			calculateDriveRoute();
			break;
		// 模拟
		case R.id.pop_simulate:
			isNaviRote = true;
			calculateDriveRoute();
			break;
		// 返回按钮监听
		case R.id.icon_iv:
			finish();
			break;
		// 语音按钮
		case R.id.Speech_Navi:
			iatController.start();
			break;
		case R.id.goBack:
			finish();
			break;
		// case R.id.seachButton:
		// String strSerach = serchEditText.getText().toString().trim();
		// if (strSerach.length() == 0) {
		// showToastL("搜索框内容不能为空！");
		// return;
		// }
		// doSearchQuery(strSerach);
		// break;
		default:
			break;
		}

	}

	// 计算驾车路线
	private void calculateDriveRoute() {
		if (!isCalculateSuccess) {
			showProgressDialog("提示", "路径计算中请稍后...");
			isCalculateSuccess = mAMapNavi.calculateDriveRoute(mStartPoints, mEndPoints, null, AMapNavi.DrivingFastestTime);
			if (!isCalculateSuccess) {
				showToast("路线计算失败,检查参数情况");
			}
		} else {

		}

	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
	}

	@Override
	public View getInfoContents(Marker arg0) {
		View infoContent = null;
		switch (inNaviLocionType) {
		case Constants.inNaviLocionType_COLLECTION:
			infoContent = getLayoutInflater().inflate(R.layout.pop_car_address_set, null);
			break;
		case Constants.inNaviLocionType_COMMON:
			infoContent = getLayoutInflater().inflate(R.layout.pop_car_address_navigation, null);
			break;
		case Constants.inNaviLocionType_DIRECT:
			infoContent = getLayoutInflater().inflate(R.layout.pop_car_address_navigation_location, null);
			break;

		default:
			break;
		}

		return infoContent;
	}

	@Override
	public View getInfoWindow(final Marker marker) {
		return initInfoWindow(marker);
	}

	private View initInfoWindow(final Marker marker) {
		View infoWindow = null;
		switch (inNaviLocionType) {

		case Constants.inNaviLocionType_COLLECTION:
			infoWindow = getLayoutInflater().inflate(R.layout.pop_car_address_set, null);
			break;
		case Constants.inNaviLocionType_COMMON:
			infoWindow = getLayoutInflater().inflate(R.layout.pop_car_address_navigation, null);
			Toast.makeText(NaviLocationActivity.this, mAddressEntity.getNick_address() + " " + mAddressEntity.getReal_address(), Toast.LENGTH_LONG).show();
			((TextView) infoWindow.findViewById(R.id.address_name)).setText(mAddressEntity.getNick_address());
			((TextView) infoWindow.findViewById(R.id.address)).setText(mAddressEntity.getReal_address());
			if (strAllLength == null) {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText("到这里");
			} else {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText(strAllLength + "公里");
			}

			break;
		case Constants.inNaviLocionType_DIRECT:
			infoWindow = getLayoutInflater().inflate(R.layout.pop_car_address_navigation_location, null);
			break;

		default:
			break;
		}

		RelativeLayout pop_address_nav_rl = (RelativeLayout) infoWindow.findViewById(R.id.pop_address_nav_rl);

		if (isGetInfoWindow) {
			isGetInfoWindow = false;
			// String strAddress_name = "";
			if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
				// strAddress_name = serchEditText.getText().toString().trim();
				((TextView) infoWindow.findViewById(R.id.address_name)).setText(serchEditText.getText().toString().trim());
				((TextView) infoWindow.findViewById(R.id.address)).setText(strAddress);
			}

		}

		pop_address_nav_rl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (inNaviLocionType != Constants.inNaviLocionType_COLLECTION) {
					showPOP(marker);
				} else {
					Intent emulatorIntent = new Intent(NaviLocationActivity.this, ComAddressSetavt.class);
					Bundle bundle = new Bundle();
					bundle.putString("areaid", serchEditText.getText().toString());// 地区
					bundle.putString("address", strAddress);// 实际地址
					bundle.putString("longitude", mEndPoint.getLongitude() + "");
					bundle.putString("latitude", mEndPoint.getLatitude() + "");
					emulatorIntent.putExtras(bundle);
					startActivity(emulatorIntent);
					finish();
				}
				// if (inNaviLocionType !=
				// Constants.inNaviLocionType_COLLECTION) {
				//
				// } else {
				// Intent emulatorIntent = new Intent(
				// NaviLocationActivity.this, ComAddressSetavt.class);
				// Bundle bundle = new Bundle();
				// bundle.putSerializable("areaid", serchEditText.getText()
				// .toString());// 地区
				// bundle.putSerializable("address", strAddress);// 实际地址
				// bundle.putSerializable("longitude",
				// mEndPoint.getLongitude());
				// bundle.putSerializable("latitude", mEndPoint.getLatitude());
				// emulatorIntent.putExtras(bundle);
				// startActivity(emulatorIntent);
				// }

			}
		});
		return infoWindow;

	}

	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		dismissProgressDialog();
		Toast.makeText(NaviLocationActivity.this, "路径计算失败", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onCalculateRouteSuccess() {
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null || mAMapNavi.getNaviGuideList() == null) {
			return;
		}
		// 存放本地
		// ArrayList<ArrayList<String>> arrayList = new
		// ArrayList<ArrayList<String>>();
		// HashMap<String, ArrayList<NaviLatLng>> map = new HashMap<String,
		// ArrayList<NaviLatLng>>();
		// for (int i = 0; i < naviPath.getSteps().size(); i++) {
		// ArrayList<String> naviLatLngs = new ArrayList<String>();
		// for (int j = 0; j < naviPath.getSteps().get(i).getLink().size(); j++)
		// {
		// for (int j2 = 0; j2 < naviPath.getSteps().get(i).getLink()
		// .get(j).getCoords().size(); j2++) {
		// naviLatLngs.add(naviPath.getSteps().get(i).getLink().get(j)
		// .getCoords().get(j2).getLatitude()
		// + " "
		// + naviPath.getSteps().get(i).getLink().get(j)
		// .getCoords().get(j2).getLongitude());
		// }
		// }
		// if (arrayList != null) {
		// ArrayList<String> list = new ArrayList<String>();
		// list.add("&&");
		// arrayList.add(list);
		// }
		// arrayList.add(naviLatLngs);
		// }
		// SDCardTools.comparisonFile();
		// String fileName = SDCardTools.getFilePath() + "/"
		// + System.currentTimeMillis() + ".txt";
		// File file = new File(fileName);
		// try {
		// FileOutputStream fos = new FileOutputStream(file, true);
		// fos.write(arrayList.toString().getBytes());
		// fos.flush();
		// fos.close();
		// // postReport(file);
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// if (aMapNaviGuides == null) {
		// aMapNaviGuides = new ArrayList<String>();
		// } else {
		// aMapNaviGuides.clear();
		// }
		// for (AMapNaviGuide mapNaviGuide : mAMapNavi.getNaviGuideList()) {
		// aMapNaviGuides.add(mapNaviGuide.getLength() + "");
		// }
		// strAllLength = naviPath.getAllLength() + "";
		// if (inNaviLocionType == Constants.inNaviLocionType_COMMON) {
		// // View infoWindow = getLayoutInflater().inflate(
		// // R.layout.pop_car_address_navigation, null);
		// //
		// ((TextView)infoWindow.findViewById(R.id.pop_address_nav_tv)).setText("1111111");
		// mEndMarker.showInfoWindow();
		// // 获取路径规划线路，显示到地图上
		// mRouteOverLay.setRouteInfo(naviPath);
		// mRouteOverLay.addToMap();
		// mIsCalculateRouteSuccess = true;
		//
		// }else {
		// new calculateRouteThread(naviPath, entity).start();
		// }

		HUDParameterEntity entity = new HUDParameterEntity();
		new calculateRouteThread(naviPath, entity).start();
	}

	// private void calculateRoute(AMapNaviPath naviPath, HUDParameterEntity
	// entity) {
	//
	// BluetoothUpdataObserver.getCommunicationUpdata().CommunicationUpdata(
	// Bluetooth.initMark);
	// NaviLatLng startLatLng = naviPath.getStartPoint();
	// List<NaviLatLng> CoordList = naviPath.getCoordList();
	// int latLngsSize = CoordList.size();
	// // 判断是否大于50个坐标
	// if (latLngsSize > 50) {
	// // 先整除
	// for (int i = 0; i < latLngsSize / 50; i++) {
	// service.sendMessage(HUDParameterEntity.toArrayList(getRoult(
	// CoordList.size(),
	// CoordList.subList(50 * i, 50 * (i + 1)), startLatLng,
	// naviPath)),
	// Constants.ZXSendHudDataBeforTypeWithStart);
	// }
	// // 判断是否有余数
	// if (latLngsSize % 50 > 0) {
	// service.sendMessage(HUDParameterEntity.toArrayList(getRoult(
	// CoordList.size(), CoordList.subList(latLngsSize
	// - latLngsSize % 50, latLngsSize), startLatLng,
	// naviPath)),
	// Constants.ZXSendHudDataBeforTypeWithStart);
	// }
	// } else {
	// service.sendMessage(HUDParameterEntity.toArrayList(getRoult(
	// CoordList.size(), CoordList, startLatLng, naviPath)),
	// Constants.ZXSendHudDataBeforTypeWithStart);
	// }
	//
	// // 坐标发送完毕后开始发送导航开始
	// BluetoothUpdataObserver.getCommunicationUpdata().CommunicationUpdata(
	// Bluetooth.startMark);
	// startEmulatorNavi(CoordList);
	// }

	private void startEmulatorNavi() {
		dismissProgressDialog();
		Intent emulatorIntent = new Intent(NaviLocationActivity.this, SimpleNaviActivity.class);
		Bundle bundle = new Bundle();
		bundle.putBoolean(Utils.ISEMULATOR, isNaviRote);
		bundle.putStringArrayList("aMapNaviGuides", (ArrayList<String>) aMapNaviGuides);
		// bundle.putParcelableArrayList("CoordList",
		// (ArrayList<? extends Parcelable>) CoordList);
		bundle.putParcelable("mNaviStart", mStartPoint);
		bundle.putInt(Utils.ACTIVITYINDEX, Utils.SIMPLEROUTENAVI);
		emulatorIntent.putExtras(bundle);
		emulatorIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(emulatorIntent);

	}

	/**
	 * 开始组装上传数据
	 */
	private HUDParameterEntity getRoult(int NaviLatLngSize, List<NaviLatLng> latLngs, NaviLatLng startLatLng, AMapNaviPath naviPath) {

		HUDParameterEntity hudParameterEntity = new HUDParameterEntity();
		if (NaviLatLngSize > 0) {
			hudParameterEntity.setNav_amp_router_locs_count(NaviLatLngSize + "");
		}
		hudParameterEntity.setNav_amp_router_locs(LongitudeAndLatitudeTools.getLongitudeAndLatitude(latLngs, startLatLng));
		Log.i(TAG, hudParameterEntity.toArrayList(hudParameterEntity));
		return hudParameterEntity;
	}

	@Override
	public void onEndEmulatorNavi() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	/**
	 * 用户手机GPS设置是否开启的回调函数。
	 */
	@Override
	public void onGpsOpenStatus(boolean arg0) {

	}

	/**
	 * 开启GPS
	 */
	private void openGPSDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage("是否开启GPS");
		builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SystemTools.openGPS(NaviLocationActivity.this);
			}
		});
		builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.show();

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {
		System.out.println("aaaaaa");
	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	@Deprecated
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForYaw() {
		//

	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub

	}

	/**
	 * 计算行车路径的线程
	 */
	class calculateRouteThread extends Thread {
		AMapNaviPath naviPath = null;
		HUDParameterEntity hudParameterEntity = null;

		public calculateRouteThread(AMapNaviPath naviPath, HUDParameterEntity entity) {
			this.naviPath = naviPath;
			this.hudParameterEntity = entity;
		}

		@SuppressWarnings("static-access")
		@Override
		public void run() {
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.initMark);
			// NaviLatLng startLatLng = naviPath.getStartPoint();
			// List<NaviLatLng> CoordList = naviPath.getCoordList();
			// if (CoordList == null) {
			// CoordList = new ArrayList<NaviLatLng>();
			// }
			//
			// int latLngsSize = CoordList.size();
			// if (latLngsSize > 49) {
			// latLngsSize = 49;
			// }
			// 开始导航标志
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.startMark);
			// 暂时不用发送坐标点
			// service.getConsumer().add(
			// new MessageTask(service, HUDParameterEntity
			// .toArrayList(getRoult(CoordList.size(),
			// CoordList.subList(0, latLngsSize),
			// startLatLng, naviPath)),
			// Constants.ZXSendHudDataBeforTypeWithStart));
			startEmulatorNavi();
		}
	}

	// private UartService getUartService() {
	// if (service == null) {
	// service = BluetoothGattTools.getUartService();
	// }
	// return service;
	//
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == IatrequestCode) {
			isBack = true;
			Bundle bundle = data.getExtras();
			if (bundle != null) {

				PoiItem poi = bundle.getParcelable("poi");
				// 搜索完毕后根据坐标点画出
				addPointToMap(new LatLng(poi.getLatLonPoint().getLatitude(), poi.getLatLonPoint().getLongitude()));
				strAddress = poi.getTitle();
				// showToast(strAddress);
				// View infoWindow = getLayoutInflater().inflate(
				// R.layout.pop_car_address_set, null);
				// ((TextView) infoWindow
				// .findViewById(R.id.pop_company_addressset_tv)).setText(strAddress);
				isGetInfoWindow = true;
				mEndMarker.showInfoWindow();
				// serchEditText.setText(bundle.getString("IatMessage"));
				// serchEditText.setSelection(strMessage.length());
			}
		}
	}

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			System.out.println(error.getPlainDescription(true));
		}

	};

	private void printResult(RecognizerResult results) {
		String text = JsonParser.parseIatResult(results.getResultString());
		JSONObject resultJson = null;
		String sn = null;
		// 读取json结果中的sn字段
		try {
			resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mIatResults.put(sn, text);
		final StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		}
		String result = resultBuffer.toString();

		for (int i = 0; i < redundantCharacter.length; i++) {
			int index = resultBuffer.indexOf(redundantCharacter[i]);
			if (index > -1) {
				result = resultBuffer.substring(index + 1);
			}
		}
		if (result.length() != 0 && ((Boolean) resultJson.opt("ls"))) {
			Log.i(TAG, "语音识别：" + result.toString());
			doSearchQuery(result);
		}

		// Inputtips inputtips = new Inputtips(NaviLocationActivity.this,
		// new InputtipsListener() {
		// @Override
		// public void onGetInputtips(List<Tip> list, int arg1) {
		// tips.clear();
		// if (isBack) {
		// if (list != null && list.size() != 0) {
		// tips.addAll(list);
		//
		// } else if (resultBuffer != null
		// && resultBuffer.length() != 0) {
		// Tip tip = new Tip();
		// tip.setName(resultBuffer.toString());
		// tips.add(tip);
		// }
		//
		// Intent intent = new Intent(
		// NaviLocationActivity.this,
		// IatActivity.class);
		// Bundle bundle = new Bundle();
		// bundle.putParcelableArrayList("tips",
		// (ArrayList<? extends Parcelable>) tips);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, IatrequestCode);
		// isBack = false;
		// }
		//
		// }
		// });
		// try {
		// inputtips.requestInputtips(result, SystemInfo.City);
		// } catch (AMapException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(String reslut) {
		int currentPage = 0;
		query = new PoiSearch.Query(reslut, "", SystemInfo.City);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);// 设置查第一页
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
		if (navigationPopupWindow != null && navigationPopupWindow.isShowing()) {
			navigationPopupWindow.dismiss();
		}
		isBack = true;
		// 移动数据统计分析
		FlowerCollector.onResume(NaviLocationActivity.this);
		FlowerCollector.onPageStart(TAG);

		if (!SystemTools.isOPenGPS(NaviLocationActivity.this)) {
			openGPSDialog();
		}

	}

	@Override
	protected void onPause() {

		super.onPause();
		mapView.onPause();
		deactivate();

		// 移动数据统计分析
		FlowerCollector.onPageEnd(TAG);
		FlowerCollector.onPause(NaviLocationActivity.this);
		super.onPause();
	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		strAddress = "";
		if (rCode == 0) {
			Log.i(TAG, "POI搜索成功");
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
					if (poiItems != null && poiItems.size() > 0) {
						Intent intent = new Intent(NaviLocationActivity.this, IatActivity.class);
						Bundle bundle = new Bundle();
						bundle.putParcelableArrayList("poi", (ArrayList<? extends Parcelable>) poiItems);
						intent.putExtras(bundle);
						startActivityForResult(intent, IatrequestCode);
						isBack = false;
						// aMap.clear();// 清理之前的图标
						// PoiOverlay poiOverlay = new PoiOverlay(aMap,
						// poiItems);
						// poiOverlay.removeFromMap();
						// poiOverlay.addToMap();
						// poiOverlay.zoomToSpan();
					} else if (suggestionCities != null && suggestionCities.size() > 0) {
						// showSuggestCity(suggestionCities);
						showToast("这里没有搜索到结果推荐...");
					} else {
						showToastS(getResources().getString(R.string.no_result).toString());
					}
				}
			} else {
				showToastS(getResources().getString(R.string.no_result).toString());
			}
		} else if (rCode == 27) {
			showToastS(getResources().getString(R.string.error_network).toString());
		} else if (rCode == 32) {
			showToastS(getResources().getString(R.string.error_key).toString());
		} else {
			showToastS(getResources().getString(R.string.error_other).toString());
		}

	}

	@Override
	public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideCross() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideLaneInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showCross(AMapNaviCross arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1, byte[] arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	@Deprecated
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void notifyParallelRoad(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onArriveDestination(NaviStaticInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCalculateMultipleRoutesSuccess(int[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeStatistics(AimLessModeStat arg0) {
		// TODO Auto-generated method stub
		
	}


}